package com.param_validate_demo.validator;

import com.param_validate_demo.annotation.AgeValidate;
import com.param_validate_demo.enums.GenderEnum;
import com.param_validate_demo.model.User;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class AgeValidator implements ConstraintValidator<AgeValidate, Object> {
    @Override
    public void initialize(AgeValidate constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object target, ConstraintValidatorContext constraintValidatorContext) {
        if (target instanceof User) {
            User user = (User) target;
            if (StringUtils.isBlank(user.getGender())) {
                return true;
            }
            if (GenderEnum.MALE.getCode().equals(user.getGender())) {
                return user.getAge() >= 22;
            }
            if (GenderEnum.FEMALE.getCode().equals(user.getGender())) {
                return user.getAge() >= 20;
            }

        }
        return false;
    }
}
